package com.mycode.skill.commom;

import com.mycode.skill.commom.enums.ResponseCodeEnum;
import org.slf4j.MDC;

import java.util.Optional;

/**
 *
 * @author Qhy
 * @date 2023/12/12
 */
public record RestBean<T> (long id, int code, T data, String message) {
    public static <T> RestBean<T> success(T data){
        return new RestBean<>(requestId(), ResponseCodeEnum.SUCCESS.value, data, "请求成功");
    }

    public static <T> RestBean<T> success(){
        return success(null);
    }

    public static <T> RestBean<T> forbidden(String message){
        return failure(ResponseCodeEnum.FORBIDDEN.value, message);
    }

    public static <T> RestBean<T> unauthorized(String message){
        return failure(ResponseCodeEnum.UNAUTHORIZED.value, message);
    }

    public static <T> RestBean<T> exception(String message){
        return failure(ResponseCodeEnum.EXCEPTION.value, message);
    }

    public static <T> RestBean<T> failure(int code, String message){
        return new RestBean<>(requestId(), code, null, message);
    }


    /**
     * 获取当前请求ID方便快速定位错误
     * @return ID
     */
    private static long requestId(){
        String requestId = Optional.ofNullable(MDC.get("reqId")).orElse("0");
        return Long.parseLong(requestId);
    }

}
